package com.han.yrpc.core.consumer;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class ConsumerBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            YrpcConsumer yrpcConsumer = field.getAnnotation(YrpcConsumer.class);
            if (yrpcConsumer != null) {
                Object proxyInstance = ServiceProxy.getProxy(field.getType());
                field.setAccessible(true);
                try {
                    field.set(bean, proxyInstance);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return bean;
    }
}
